        <template>
            <el-main height="">
                <!-- Main content -->
                <el-form :model="searchParms" :inline="true" size="default">
                    <el-form-item label="">
                        <el-input placeholder="输入商品名称" v-model="searchParms.goodsName">
                            <template #suffix>
                                <el-button icon="CloseBold" @click="resetBtn" type="text"
                                    style="padding: 0;"></el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <!-- <el-button icon="CloseBold" @click="resetBtn" type="danger" plain></el-button> -->
                        <el-button icon="Search" @click="searchBtn">搜索</el-button>
                        <!-- <el-button type="primary" icon="CirclePlus" @click="addBtn">新增</el-button> -->
                    </el-form-item>
                </el-form>
                <!-- 商品分类表格 -->
                <el-table :data="tableList" :height="tableHight" border stripe>
                    <el-table-column prop="goodsId" label="商品Id">
                    </el-table-column>
                    <el-table-column prop="goodsName" label="商品名称">
                    </el-table-column>
                    <el-table-column prop="categoryName" label="商品分类">
                    </el-table-column>
                    <el-table-column prop="introduce" label="简介">
                    </el-table-column>
                    <el-table-column prop="image" label="商品图片">
                        <template #default="scope">
                            <el-image v-if="scope.row.image" style="width: 100px; height: 100px;"
                            :src="scope.row.image.split(',')[0]">
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="商品价格"> </el-table-column>
                    <el-table-column label="联系方式">
                        <template #default="{ row }">
                            <div>电话: {{ row.phoneNum }}</div>
                            <div>微信: {{ row.wechatId }}</div>
                        </template>
                    </el-table-column>

                    <el-table-column label="商品状态">
                        <template #default="scope">
                            <!-- <el-tag type="success" size="default" v-if="scope.row.status == 1">已上架</el-tag>
                            <el-tag type="warning" size="default" v-if="scope.row.status == 0">已下架</el-tag> -->
                            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                                @change="handleStatusChange(scope.row)"></el-switch>
                            <span style="margin-left: 8px;">
                                {{ scope.row.status === 1 ? '已上架' : '已下架' }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作">
                        <template #default="scope">
                            <!-- <el-tag type="primary" size="default" @click="editBtn(scope.row)">编辑</el-tag> -->
                            <el-tag type="danger" size="default" @click="delBtn(scope.row)">删除</el-tag>
                        </template>
                    </el-table-column>

                </el-table>
                <!-- 实现底部分页功能 -->
                <el-pagination @size-change="sizeChange" @current-change="currentChange"
                    :current-page.sync="searchParms.currentPage" :page-sizes="[10, 20, 40, 80, 100]"
                    :page-size="searchParms.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="searchParms.total">
                    :pager-count="7">
                </el-pagination>

                <!-- 新增商品弹窗 -->
                <SysDialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
                    @on-close="onClose" @on-confirm="submitForm">

                    <template v-slot:content>
                        <el-form :model="addModel" ref="addRef" :rules="rules" label-width="80px" :inline="false"
                            size="default">
                            <!-- prop字段绑定的名称和addModel绑定的名称要一致 -->
                            <!-- <el-form-item prop="serialNum" label="排序序号">
                                <el-input v-model="addModel.serialNum"></el-input>
                            </el-form-item>
                            <el-form-item prop="categoryName" label="分类名称">
                                <el-input v-model="addModel.categoryName"></el-input>
                            </el-form-item> -->


                        </el-form>
                    </template>
                </SysDialog>
            </el-main>

        </template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue';
import useDialog from '@/hooks/useDialog';
import SysDialog from '@/components/SysDialog.vue';
import { ElMessage, FormInstance } from 'element-plus';
import { addGoodsApi, queryGoodsListApi, onShelfGoodsApi, offShelfGoodsApi, editGoodsApi, deleteGoodsApi } from "@/api/goods/index"
import { totalmem } from 'os';
import { GoodsCategory } from "@/api/category/CategoryModel"
import { on } from 'events';
import { EditType, Title } from "@/type/BaseEnum";
import useInstance from '@/hooks/useInstance';
import { Goods } from '@/api/goods/GoodsModel';

// 全局变量
const { global } = useInstance()
// 表单ref属性
const addRef = ref<FormInstance>();
// 弹窗绑定对象
const { dialog, onClose, onShow } = useDialog();
// 搜索绑定对象 与listparm中对应，大小写一致
const searchParms = reactive({
    currentPage: 1,
    pageSize: 10,
    goodsName: '',
    total: 0
});
// 新增绑定对象
const addModel = reactive({
    goodsId: 0,
    goodsName: '',
    introduce: '',
    userId: 0,
    categoryId: 0,
    categoryName: '',
    price: 0,
    image: '',
    phoneNum: '',
    wechatId: '',
    createdAt: '',
    updatedAt: '',
    status: 1
});

// 表单验证规则
const rules = reactive({
    // serialNum: [{ required: true, message: "输入商品分类序号", trigger: "blur" }],
    // categoryName: [{ required: true, message: "输入商品分类名称", trigger: "blur" }],

});
// 新增按钮点击事件
const addBtn = () => {
    editFlag.value = "0";
    console.log("新增按钮点击事件");
    dialog.height = 280;
    onShow();
    // 新增编辑用的同一个弹框，使用新增时需清空表单
    addRef.value?.resetFields();
};
// 搜索按钮点击事件
const searchBtn = () => {
    console.log("搜索按钮点击事件");
    queryGoodsList();
};
// 重置按钮点击事件
const resetBtn = () => {
    console.log("重置按钮点击事件");
    searchParms.goodsName = "";
    searchParms.currentPage = 1;
    queryGoodsList();
};
// 表单提交
const submitForm = () => {
    addRef.value?.validate(async (valid) => {
        if (valid) {
            console.log("表单验证成功");
            // 提交
            let result = null;
            result = await addGoodsApi(addModel);
            if (result && result.code == 200) {
                ElMessage.success("新增成功");
                queryGoodsList();
                onClose();
            }
        } else {
            console.log("表单验证失败");
        }
    });
};
// 表格数据
const tableList = ref([]);
const tableHight = ref(0);
// 新增or编辑判断标志 0新增 1编辑
const editFlag = ref("");
// 获取表格数据
const queryGoodsList = async () => {
    const result = await queryGoodsListApi(searchParms);
    // console.log(searchParms)
    if (result && result.code == 200) {
        console.log("获取列表数据成功", result.data.records);
        tableList.value = result.data.records;
        searchParms.total = result.data.total;

    }
};
// 处理商品状态切换
const handleStatusChange = async (row: Goods) => {
    try {
        let result;
        if (row.status == 1) {
            result = await onShelfGoodsApi(row.goodsId); // 上架
        } else {
            result = await offShelfGoodsApi(row.goodsId); // 下架
        }
        if (result && result.code == 200) {
            ElMessage.success(row.status === 1 ? "上架成功" : "下架成功");
            queryGoodsList(); // 刷新列表
        } else {
            ElMessage.error("操作失败");
            // 如果操作失败，恢复原来的状态
            row.status = row.status === 1 ? 0 : 1;
        }
    } catch (error) {
        ElMessage.error("操作失败");
        // 如果操作失败，恢复原来的状态
        row.status = row.status === 1 ? 0 : 1;
    }
};
// 编辑按钮点击事件
const editBtn = (row: GoodsCategory) => {
    editFlag.value = "1";
    dialog.height = 450;
    console.log("编辑按钮点击事件", row);
    onShow();
    // 赋值表单数据
    nextTick(() => {
        Object.assign(addModel, row);
    });

    // 标题
    dialog.title = Title.EDIT;
    dialog.visible = true;


};
// 新增or编辑表单提交事件
const commitAdd = () => {
    addRef.value?.validate(async (valid) => {
        if (valid) {
            console.log(addModel);
            // 判断是新增还是编辑
            let result = null;
            if (editFlag.value == EditType.ADD) {
                console.log("新增");
                // 调用新增接口
                result = await addGoodsApi(addModel);
            } else {
                console.log("编辑");
                // 调用编辑接口
                result = await editGoodsApi(addModel);
            }
            // 新增成功或编辑成功
            if (result && result.code == 200) {
                console.log("返回code成功");
                ElMessage.success(result.msg);
                // 刷新列表数据
                queryGoodsList();

                // 关闭弹窗
                dialog.visible = false;
                console.log("提交成功");
                onClose();
            }
        } else {
            console.log("提交失败");
        }
    });
};

// 删除按钮点击事件
const delBtn = async (row: Goods) => {
    console.log("删除按钮点击事件", row);
    // 找到$confirm 
    console.log(global)
    // 注意async和await成对使用
    const confirm = await global.$myconfirm("确认删除吗？");
    if (confirm) {
        const result = await deleteGoodsApi(row.goodsId);
        if (result && result.code == 200) {
            console.log("删除成功");
            ElMessage.success(result.msg);
            // 刷新列表数据
            queryGoodsList();
        }
    } else {
        console.log("取消删除");
    }

};
// 页码大小改变事件
const sizeChange = (pageSize: number) => {
    console.log("页码大小改变事件", pageSize);

};
// 页码改变事件
const currentChange = (currentPage: number) => {
    console.log("页码改变事件", currentPage);
    searchParms.currentPage = currentPage;
    queryGoodsList();
};
// 页面加载完成后重新获取表格数据
onMounted(() => {
    queryGoodsList();
    nextTick(() => {
        tableHight.value = document.documentElement.clientHeight - 200;
        // tableHight.value = window.innerHeight - 200;
    });
});
</script>

<style scoped></style>